package com.heima.search.interceptor;


import com.heima.model.common.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.threadLocal.WmThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;


public class ApTokenInterceptor implements HandlerInterceptor  {


    /**
     *在执行具体的业务方法之前执行该方法
     * @param request 请求对象
     * @param response 响应对象
     * @param handler
     * @return true表示放行，false表示拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //1.从请求头中获取token
        String token = request.getHeader("token");

        //2校验token是否有值
        Optional<String> optional = Optional.ofNullable(token);
        if(optional.isPresent()) {
            //2.解析token,得到载核获取用户id
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            Integer userId = (Integer) claimsBody.get("id");
            //3.存入threadLocal中
            WmUser wmUser = new WmUser();
            wmUser.setId(userId);
            WmThreadLocalUtil.setUser(wmUser);
        }

        return true;
    }

    /**
     *在执行具体的业务方法之后执行该方法
     * @param request 请求对象
     * @param response 响应对象
     * @param handler
     * @return true表示放行，false表示拦截
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocalUtil.deWmUser();
    }
}